package com.example.lenovo.asia5b.home.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;

import com.bigkoo.pickerview.TimePickerView;
import com.example.lenovo.asia5b.home.bean.MyDataBean;
import com.example.lenovo.asia5b.home.bean.RegionBean;
import com.example.lenovo.asia5b.ui.LoadingDalog;
import com.example.lenovo.asia5b.util.ICallBack;
import com.example.lenovo.asia5b.util.JsonTools;
import com.example.lenovo.asia5b.util.Logic;
import com.example.lenovo.asia5b.util.MD5;
import com.example.lenovo.asia5b.util.Setting;
import com.example.lenovo.asia5b.util.SharedPreferencesUtils;
import com.example.lenovo.asia5b.util.StringUtil;
import com.wushi.lenovo.asia5b.R;

import org.json.JSONArray;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import app.BaseActivity;
import fay.frame.ui.U;

import static com.wushi.lenovo.asia5b.R.id.txt_constell;

/**
 * Created by lenovo on 2017/10/21.
 */

public class WriteUserDataTwoActivity extends BaseActivity  implements ICallBack {

    List<String> countryList = null;
    List<String> stateList = null;
    List<RegionBean> lists = null;

    private ArrayAdapter<String> countryAdapter,stateAdapter;

    private LoadingDalog loadingDalog;
    //分别为地址和家乡的国家和城市名字
    private String region_name_1="",region_name_2="",hometown_name_1="",hometown_name_2="";

    private TextView activity_write_user_data_birthday;

    private Spinner activity_write_user_data_sex,activity_write_user_data_constellation,
            activity_write_user_data_address_country,activity_write_user_data_address_state,
            activity_write_user_data_home_country,activity_write_user_data_home_state;

    private String user_id;
    private MyDataBean beanHome;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_write_user_data_two);
        initView();
    }

    public void initView(){
        loadingDalog = new LoadingDalog(this);
            F.id(R.id.activity_write_user_date_finish).clicked(this);
        F.id(R.id.btn_complete).clicked(this);
        activity_write_user_data_birthday = findViewById(R.id.activity_write_user_data_birthday);//生日
        activity_write_user_data_sex = findViewById(R.id.activity_write_user_data_sex);//性别
        activity_write_user_data_constellation = findViewById(R.id.activity_write_user_data_constellation);//星座
        activity_write_user_data_address_country = findViewById(R.id.activity_write_user_data_address_country);//住址国家
        activity_write_user_data_address_state = findViewById(R.id.activity_write_user_data_address_state);//住址州
        activity_write_user_data_home_country = findViewById(R.id.activity_write_user_data_home_country);//家乡国家
        activity_write_user_data_home_state = findViewById(R.id.activity_write_user_data_home_state);//家乡州
        activity_write_user_data_birthday.setOnClickListener(this);
        Intent intent = getIntent();
        user_id = intent.getStringExtra("user_id");
//        if (!intent.hasExtra("register")) {
            myInfoData();
//        }else {
//            regionList();
//        }

    }

    /**
     * 获取个人资料接口
     */
    public void myInfoData() {
        loadingDalog.show();
        try {
            Map<String, String> parmaMap = new HashMap<String, String>();
            String url = Setting.MY_INF0;
            Date date = new Date();
            String time = String.valueOf(date.getTime());
            String[] sort = {"user_id"+user_id,"time"+time};
            String sortStr = Logic.sortToString(sort);
            String md5_32 = MD5.MD5EncryptionFor32(MD5.MD5EncryptionFor32(sortStr));//二次加密
            parmaMap.put("user_id", user_id);
            parmaMap.put("time",time);
            parmaMap.put("sign",md5_32);
            JsonTools.getJsonAll(this, url, parmaMap, 1);
        }catch (Exception e) {

        }
    }


    /**
     * 调用修改资料接口
     */
    private void getPostAPI(){
        try {
            String birthday = activity_write_user_data_birthday.getText().toString();//生日
            long sex = activity_write_user_data_sex.getSelectedItemId();//性别
            String[] items = getResources().getStringArray(R.array.constellation);//星座
            String constellID = "1";//星座ID
            for (int i = 1; i < items.length; i++) {
                if (items[i].equals(F.id(txt_constell).getText().toString())){
                    constellID = i+"";
                    break;
                }
            }
            String addressCountry = (String) activity_write_user_data_address_country.getSelectedItem();//住址国家
            String addressState = (String) activity_write_user_data_address_state.getSelectedItem();//住址州
            String homeCountry = (String) activity_write_user_data_home_country.getSelectedItem();//家乡国家
            String homeState = (String) activity_write_user_data_home_state.getSelectedItem();//家乡州


            String myDataURL = Setting.UPDA_INFO;
            Map<String, String> map = new HashMap<String, String>();
            map.put("user_id", user_id);//用户id
            map.put("user_name", beanHome.user_name);//昵称
            map.put("nickname", beanHome.nickname);//昵称
            map.put("alias", beanHome.alias);//姓名
            map.put("sex", String.valueOf(sex));//性别
            map.put("birthday", birthday);//生日
            map.put("constell", constellID);//星座
            //地址国家
            String live_country = "";
            if (!TextUtils.equals(getResources().getString(R.string.qxz), addressCountry)) {
                for (RegionBean regionBean : lists) {
                    if (TextUtils.equals(addressCountry, regionBean.region_name)) {
                        live_country = regionBean.region_id;
                    }
                }
            }
            map.put("live_country", live_country);
            //地址州
            String live_province = "";
            if (!TextUtils.equals(getResources().getString(R.string.qxz), addressState)) {
                for (RegionBean regionBean : lists) {
                    List<RegionBean> regionList = regionBean.chile;
                    for (RegionBean region : regionList) {
                        if (TextUtils.equals(addressState, region.region_name)) {
                            live_province = region.region_id;
                        }
                    }
                }
            }
            map.put("live_province", live_province);
            //家乡国家
            String home_country = "";
            if (!TextUtils.equals(getResources().getString(R.string.qxz), homeCountry)) {
                for (RegionBean regionBean : lists) {
                    if (TextUtils.equals(homeCountry, regionBean.region_name)) {
                        home_country = regionBean.region_id;
                    }
                }
            }
            map.put("home_country", home_country);
            //家乡州
            String home_province = "";
            if (!TextUtils.equals(getResources().getString(R.string.qxz), homeState)) {
                for (RegionBean regionBean : lists) {
                    List<RegionBean> regionList = regionBean.chile;
                    for (RegionBean region : regionList) {
                        if (TextUtils.equals(homeState, region.region_name)) {
                            home_province = region.region_id;
                        }
                    }
                }
            }
            map.put("home_province", home_province);
            map.put("email", beanHome.email);//邮件
//                                map.put("mobile_phone",mobile_phone);//手机

            Date date = new Date();
            String time = String.valueOf(date.getTime());
            map.put("time", time);

            String[] sortStr = {"user_id" + user_id, "nickname" + beanHome.nickname, "alias" + beanHome.alias, "sex" + String.valueOf(sex),
                    "birthday" + birthday, "constell" + constellID, "live_country" + live_country,
                    "live_province" + live_province, "home_country" + home_country, "home_province" + home_province,
                    "email" + beanHome.email, "time" + time};
            String sotr = Logic.sortToString(sortStr);
            String md5 = MD5.MD5EncryptionFor32(MD5.MD5EncryptionFor32(sotr));
            map.put("sign", md5);

            JsonTools.getJsonAll(this, myDataURL, map, 3);
        } catch (Exception e) {

        }
    }
    @Override
    public void onClick(View v) {
        Intent intent = null;
        switch (v.getId()) {
            case R.id.activity_write_user_data_birthday://生日
                TimePickerView pvTime = new TimePickerView.Builder(WriteUserDataTwoActivity.this, new TimePickerView.OnTimeSelectListener() {
                    @Override
                    public void onTimeSelect(Date date2, View v) {//选中事件回调
                        String time = getTime(date2);
                        F.id(txt_constell).text(StringUtil.constell(WriteUserDataTwoActivity.this,time));
                        F.id(activity_write_user_data_birthday).text(time);
                    }
                })
                        .setType(TimePickerView.Type.YEAR_MONTH_DAY)//默认全部显示
                        .setCancelText(getResources().getString(R.string.qx))//取消按钮文字
                        .setSubmitText(getResources().getString(R.string.confirm))//确认按钮文字
                        .setContentSize(16)//滚轮文字大小
                        .setOutSideCancelable(true)//点击屏幕，点在控件外部范围时，是否取消显示
                        .isCyclic(true)//是否循环滚动
                        .setSubmitColor(ContextCompat.getColor(WriteUserDataTwoActivity.this,R.color.wathet))//确定按钮文字颜色
                        .setCancelColor(ContextCompat.getColor(WriteUserDataTwoActivity.this,R.color.wathet))//取消按钮文字颜色
                        .setLabel(getResources().getString(R.string.n),getResources().getString(R.string.y),getResources().getString(R.string.r),
                                getResources().getString(R.string.s),getResources().getString(R.string.f),"秒")
                        .isCenterLabel(false)
                        .build();
                pvTime.setDate(Calendar.getInstance());//注：根据需求来决定是否使用该方法（一般是精确到秒的情况），此项可以在弹出选择器的时候重新设置当前时间，避免在初始化之后由于时间已经设定，导致选中时间与当前时间不匹配的问题。
                pvTime.show();
                break;
            case R.id.activity_write_user_date_finish://完成
                finishAll();
                intent = new Intent(WriteUserDataTwoActivity.this,MainActivity.class);
                startActivity(intent);
                finish();
                break;
            case R.id.btn_complete:
                getPostAPI();
                break;
        }
    }

    /**
     * 地址名称接口
     */
    public void regionList() {
        Map<String, String> parmaMap = new HashMap<String, String>();
        String url = Setting.REGION_LIST;
        JsonTools.getJsonAll(this, url, parmaMap, 2);
    }



    public String getTime(Date date) {//可根据需要自行截取数据显示
        SimpleDateFormat format = new SimpleDateFormat("yyy-MM-dd");
        return format.format(date);
    }


    @Override
    public void logicFinish(Object result, int action) {
        Message msg = new Message();
        msg.what = action;
        msg.obj = result.toString();
        handler2.sendMessage(msg);
    }



    private Handler handler2 = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            JSONObject result= null;
            try {
                result = new JSONObject(msg.obj.toString());
            } catch (Exception e) {
            }
            int action = msg.what;
            Intent intent = null;
            try{
                if(result != null){
                    if(action == 3){
                        JSONObject jsonObject = (JSONObject)result;
                        String state = jsonObject.getString("State");
                        if(TextUtils.equals("0",state)){
                            finishAll();
                            SharedPreferencesUtils.setObjectToShare(beanHome,"user");
                            intent = new Intent(WriteUserDataTwoActivity.this,MainActivity.class);
                            startActivity(intent);
                            finish();
                        }else if(TextUtils.equals("1",state)){
                            loadingDalog.dismiss();
                            U.Toast(WriteUserDataTwoActivity.this,getResources().getString(R.string.qmsb));
                        }else if(TextUtils.equals("2",state)){
                            loadingDalog.dismiss();
                            U.Toast(WriteUserDataTwoActivity.this,getResources().getString(R.string.cscw));
                        }else if(TextUtils.equals("3",state)){
                            loadingDalog.dismiss();
                            U.Toast(WriteUserDataTwoActivity.this,getResources().getString(R.string.my_data_hint_8));
                        }else if(TextUtils.equals("4",state)){
                            loadingDalog.dismiss();
                            U.Toast(WriteUserDataTwoActivity.this,getResources().getString(R.string.yhmycz));
                        }else if (TextUtils.equals("5",state)) {
                            U.Toast(WriteUserDataTwoActivity.this, getResources().getString(R.string.yxycz));
                        }
                        loadingDalog.dismiss();
                    }
                    else if(action == 2){
                        JSONObject json = (JSONObject) result;
                        JSONArray title = json.getJSONArray("region");
                        lists = Logic.getListToBean(title,new RegionBean());

                        countryList = new ArrayList<String>();//国家
                        countryList.add(getResources().getString(R.string.qxz)
                        );
                        stateList = new ArrayList<String>();//州

                        for (RegionBean regionBean : lists) {
                            countryList.add(regionBean.region_name);
                        }
                        countryAdapter = new ArrayAdapter<String>(WriteUserDataTwoActivity.this,R.layout.simple_list_item,countryList);
                        activity_write_user_data_address_country.setAdapter(countryAdapter);//住址国家
                        for (int i = 0; i < activity_write_user_data_address_country.getAdapter().getCount(); i++) {
                            String aa = activity_write_user_data_address_country.getAdapter().getItem(i).toString();
                            if (aa.equals(region_name_1)) {
                                activity_write_user_data_address_country.setSelection(i);
                                break;
                            }
                        }
                        activity_write_user_data_address_country.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                            @Override
                            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                                String country = countryList.get(i).trim();
                                List<String> state = new ArrayList<String>();
                                state.add(getResources().getString(R.string.qxz)
                                );
                                for (RegionBean regionBean : lists) {
                                    if(TextUtils.equals(regionBean.region_name,country)){
                                        List<RegionBean> regionList = regionBean.chile;
                                        for (RegionBean region : regionList) {
                                            state.add(region.region_name);
                                        }
                                    }
                                }
                                stateAdapter = new ArrayAdapter<String>(WriteUserDataTwoActivity.this,R.layout.simple_list_item,state);
                                activity_write_user_data_address_state.setAdapter(stateAdapter);//住址州
                                for (int arg2 = 0; arg2 < activity_write_user_data_address_state.getAdapter().getCount(); arg2++) {
                                    String aa = activity_write_user_data_address_state.getAdapter().getItem(arg2).toString();
                                    if (aa.equals(region_name_2)) {
                                        activity_write_user_data_address_state.setSelection(arg2);
                                        break;
                                    }
                                }
                            }

                            @Override
                            public void onNothingSelected(AdapterView<?> adapterView) {

                            }
                        });

                        activity_write_user_data_home_country.setAdapter(countryAdapter);//家乡国家
                        for (int i = 0; i < activity_write_user_data_home_country.getAdapter().getCount(); i++) {
                            String aa = activity_write_user_data_home_country.getAdapter().getItem(i).toString();
                            if (aa.equals(hometown_name_1)) {
                                activity_write_user_data_home_country.setSelection(i);
                                break;
                            }
                        }
                        activity_write_user_data_home_country.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                            @Override
                            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                                String country = countryList.get(i).trim();
                                List<String> state = new ArrayList<String>();
                                state.add(getResources().getString(R.string.qxz));
                                for (RegionBean regionBean : lists) {
                                    if(TextUtils.equals(regionBean.region_name,country)){
                                        List<RegionBean> regionList = regionBean.chile;
                                        for (RegionBean region : regionList) {
                                            state.add(region.region_name);
                                        }
                                    }
                                }
                                stateAdapter = new ArrayAdapter<String>(WriteUserDataTwoActivity.this,R.layout.simple_list_item,state);
                                activity_write_user_data_home_state.setAdapter(stateAdapter);//住址州
                                for (int grg2 = 0; grg2 < activity_write_user_data_home_state.getAdapter().getCount(); grg2++) {
                                    String aa = activity_write_user_data_home_state.getAdapter().getItem(grg2).toString();
                                    if (aa.equals(hometown_name_2)) {
                                        activity_write_user_data_home_state.setSelection(grg2);
                                        break;
                                    }
                                }
                            }

                            @Override
                            public void onNothingSelected(AdapterView<?> adapterView) {

                            }
                        });
                    }if (action == 1) {
                        if (null != result && result instanceof JSONObject) {
                            try {
                                JSONObject json = (JSONObject) result;
                                int state = (int) json.getInt("State");
                                if (state == 0) {
                                    JSONObject user_info = json.getJSONObject("user_info");
                                    beanHome = (MyDataBean) Logic.getBeanToJSONObject(user_info, new MyDataBean());

                                    String sex = beanHome.sex;
                                    if (sex.equals("1")) {
                                        activity_write_user_data_sex.setSelection(1);
                                    } else if (sex.equals("2")) {
                                        activity_write_user_data_sex.setSelection(2);
                                    }

                                    String birthday = beanHome.birthday;
                                    F.id(activity_write_user_data_birthday).text(birthday);

                                    String constell = beanHome.constell;
                                    F.id(txt_constell).text(constell);
                                    if(!TextUtils.isEmpty(constell)) {
                                        for (int i = 0; i < activity_write_user_data_constellation.getAdapter().getCount(); i++) {
                                            String aa = activity_write_user_data_constellation.getAdapter().getItem(i).toString();
                                            if (aa.equals(constell)) {
                                                activity_write_user_data_constellation.setSelection(i);
                                                break;
                                            }
                                        }
                                    }

                                    String live_country = beanHome.live_country;

                                    String live_province = beanHome.live_province;
                                    region_name_1 = live_country;
                                    region_name_2 = live_province;
                                    F.id(R.id.txt_address).text(live_country + "-" + live_province);

                                    String home_country = beanHome.home_country;
                                    String home_province = beanHome.home_province;

                                    hometown_name_1 = home_country;
                                    hometown_name_2 = home_province;
                                    F.id(R.id.txt_hometown).text(home_country + "-" + home_province);
                                } else if (state == 1) {
                                    U.Toast(WriteUserDataTwoActivity.this, getResources().getString(R.string.qmsb));
                                } else if (state == 2) {
                                    U.Toast(WriteUserDataTwoActivity.this, getResources().getString(R.string.cscw));
                                }
                            } catch (Exception e) {

                            }
                        } else {
//                U.Toast(MyDataActivity.this, "调用失败");
                        }
                        loadingDalog.dismiss();
                        regionList();
                    }
                }else{
                    loadingDalog.dismiss();
                    U.Toast(WriteUserDataTwoActivity.this,"result："+result);
                }

            }catch (Exception e){
                Log.e("完善资料error：",e.getMessage());
            }

        }
    };

}
